﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Umi.Web.Metadatas.ServiceStruct.http
{
    /// <summary>
    /// Http 返回
    /// </summary>
    public sealed class HttpResult : IDisposable
    {
        public HttpResult(HttpResponseMessage response, Stream body)
        {
            ResponseHeaders = new Dictionary<string, IEnumerable<string>>();
            RequestHeaders = new Dictionary<string, IEnumerable<string>>();
            StatusCode = response.StatusCode;
            this.Encoding = Encoding.UTF8;
            ReadResponseHeader(response);
            ReadRequestHeader(response);
            StreamReader reader = new StreamReader(body);
            BodyText = reader.ReadToEnd();
            body.Position = 0;
            Body = body;
        }

        private void ReadResponseHeader(HttpResponseMessage response)
        {
            if (response.Headers != null)
            {
                foreach (var item in response.Headers)
                {
                    ResponseHeaders[item.Key] = item.Value;
                }
            }
            if (response.Content?.Headers != null)
            {
                foreach (var item in response.Content.Headers)
                {
                    ResponseHeaders[item.Key] = item.Value;
                }
            }
        }

        private void ReadRequestHeader(HttpResponseMessage response)
        {
            if (response.RequestMessage?.Headers != null)
            {
                foreach (var item in response.RequestMessage.Headers)
                {
                    RequestHeaders[item.Key] = item.Value;
                }
            }
            if (response.RequestMessage?.Content?.Headers != null)
            {
                foreach (var item in response.RequestMessage.Content.Headers)
                {
                    RequestHeaders[item.Key] = item.Value;
                }
            }
        }

        /// <summary>
        /// 响应头
        /// </summary>
        public IDictionary<string, IEnumerable<string>> ResponseHeaders { get; }


        /// <summary>
        /// 请求头
        /// </summary>
        public IDictionary<string, IEnumerable<string>> RequestHeaders { get; }

        /// <summary>
        /// 响应码
        /// </summary>
        public HttpStatusCode StatusCode { get; }

        /// <summary>
        /// 响应内容
        /// </summary>
        public Stream Body { get; }

        /// <summary>
        /// 编码信息
        /// </summary>
        public Encoding Encoding { get; set; }

        /// <summary>
        /// 响应内容
        /// </summary>
        public string BodyText { get; }
        public void Dispose()
        {
            if (Body != null)
                Body.Dispose();
        }
    }
}
